//
//  ZDPhotoSelectorViewController.swift
//  ZDPhotoSelector_swift
//
//  Created by Apple on 15/11/7.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class ZDPhotoSelectorViewController: UICollectionViewController {
    
    //MARK: - layout属性
    var layout = UICollectionViewFlowLayout()
    
    //保存选中的图片
    var photos = [UIImage]()
    
    //最大可选图片数
    let maxPhotoCount = 6
    
    //选中的cell的索引
    var selectedIndex = 0
    
    //MARK: - 构造函数
    init() {
    
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareUI()
    }

    
    //MARK: - 准备UI
    private func prepareUI() {
    
        collectionView?.backgroundColor = UIColor.clearColor()
        
        layout.itemSize = CGSize(width: 80, height: 80)

        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        
        //注册cell
        collectionView?.registerClass(ZDPhotoCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
}


//当前类的延展中管理代理方法
extension ZDPhotoSelectorViewController: ZDCollectionViewCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    //MARK: - collectionView数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        /*
           photos.count < maxPhotoCount 显示 photos.count + 1
           photos.count >= maxPhotoCount 显示 photos.count
        */
        return photos.count < maxPhotoCount ? photos.count + 1 : photos.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ZDPhotoCollectionViewCell
        
        //指定代理
        if (cell.delegate == nil) {
        
            cell.delegate = self
        }
        
        if indexPath.item < photos.count {
        
            cell.image = photos[indexPath.item]
            
        }else {  //避免cell的复用造成的影响
        
            cell.image = nil
        }
        
        return cell
    }
    
    
    //MARK: - ZDCollectionViewCellDelegate方法
    func collectionViewCellDidClickAddButton(cell: ZDPhotoCollectionViewCell) {
        
        //获取当前选中cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        //获取选中的cell的索引
        selectedIndex = indexPath!.item
        
//        print(selectedIndex)
        
        //弹出系统相册
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            
            print("系统相册不可用")
            
            return
        }
        
        let pickerVc = UIImagePickerController()
        
        //指定代理 实现代理方法  否则点击相册图片会自动退出相册
        pickerVc.delegate = self
        
        //modal出来
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    func collectionViewCellDidClickRemoveButton(cell: ZDPhotoCollectionViewCell) {
        
        //需要知道点的是哪一张图片
        //获取当前选中cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        //获取选中的cell的索引
        selectedIndex = indexPath!.item
        
        //删除
        photos.removeAtIndex(selectedIndex)
        
        collectionView?.reloadData()
    
    }
    
    //MARK: - UIImagePickerControllerDelegate代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //等比缩放图片 ———— 因为原图可能比较大，影响内存
        let newImage = image.scaleImage()
        
        //重复点击同一张图片  替换
        if selectedIndex < photos.count {
        
            photos[selectedIndex] = newImage
            
        } else {   //点击加号按钮
        
            //添加图片到数组中
            photos.append(newImage)
        }
        
    
        //刷新数据
        collectionView?.reloadData()
        
        //退出系统照片库
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}



//MARK: 定义协议
@objc protocol ZDCollectionViewCellDelegate : NSObjectProtocol {

    //默认是required 
    //通过传入celll来获取当前点击的cell，也可以根据cell获取到当前的indexPath
    func collectionViewCellDidClickAddButton(cell: ZDPhotoCollectionViewCell)
    func collectionViewCellDidClickRemoveButton(cell: ZDPhotoCollectionViewCell)
    
    //如果想要定义optional 必须在protocol前面增加@objc修饰
    optional
    func test()
}


//MARK: - 自定义cell
class ZDPhotoCollectionViewCell: UICollectionViewCell {
    
    
    //MARK: - 定义代理属性
    weak var delegate: ZDCollectionViewCellDelegate?
    
    //MARK: - image属性
    var image: UIImage? {
    
        didSet {
        
            if let photo = image {
            
                addBtn.setImage(photo, forState: UIControlState.Normal)
                addBtn.setImage(photo, forState: UIControlState.Highlighted)
                
                removeBtn.hidden = false
                
            }else {   //image赋值为nil时 给addBtn重新设置图片 避免重用带来的影响
            
                addBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                addBtn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
                
                removeBtn.hidden = true
            }
        }
    }
    
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
        
        backgroundColor = UIColor.brownColor()
    
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        
        addBtn.translatesAutoresizingMaskIntoConstraints = false
        removeBtn.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["ab": addBtn, "rb": removeBtn]
        
        //添加按钮
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //删除按钮
        //水平方向与父控件右边对齐
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        //垂直方向与父控件上边对齐
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
    }
    
    
    //MARK: - 按钮点击事件
    @objc private func addBtnClick() {
    
        //调用代理方法  因为是必须实现的代理方法  所以不需要判断代理是否有实现代理方法
        delegate?.collectionViewCellDidClickAddButton(self)
    }
    
    @objc private func removeBtnClick() {
    
        delegate?.collectionViewCellDidClickRemoveButton(self)
    }
    

    //MARK: - 懒加载
    private lazy var addBtn: UIButton = {
    
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        //设置填充模式
        btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        btn.addTarget(self, action: "addBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.removeBtn.hidden = true
        
        return btn
    }()
    
    private lazy var removeBtn: UIButton = {
    
        let btn = UIButton()
    
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        btn.addTarget(self, action: "removeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()

}
